package ru.ifmo.network.skype.network;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author avhaliullin
 */
public class SecureConnectionTest {
    public void runServ() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ServerSocket serverSocket = new ServerSocket(12345);
                    Socket socket = serverSocket.accept();
                    Channel channel = new RSAConnection().wrap(new SocketChannel(socket.getInputStream(), socket.getOutputStream()));
                    byte[] buf = new byte[1];
                    for (int i = 0; i < 11; i++) {
                        if (channel.getInputStream().read(buf) < 0) {
                            System.out.println("EOF");
                        } else {
                            System.out.println(buf[0]);
                        }
                    }
                } catch (IOException e) {
                    //ignore
                }
            }
        }).start();
    }

    public void runClient() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Socket socket = new Socket("localhost", 12345);
                    Channel channel = new RSAConnection().wrap(new SocketChannel(socket.getInputStream(), socket.getOutputStream()));
                    channel.getOutputStream().write(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0});
                    channel.close();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }).start();
    }

    public static void main(String[] args) throws Exception {
        SecureConnectionTest test = new SecureConnectionTest();

        test.runServ();
        test.runClient();
    }
}
